package com.example.day14_service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("sss", "onCreate: 服务被创建");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("sss", "onDestroy: 服务被销毁");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("sss", "onStartCommand: 服务已创建可以执行一些操作");
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //开启前台服务--通知
        Intent intent1 = new Intent(this,MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,102,intent1,PendingIntent.FLAG_UPDATE_CURRENT);
        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("前台服务")
                .setContentText("这是前台服务的内容")
                .setContentIntent(pendingIntent);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            manager.createNotificationChannel(new NotificationChannel("id","name",NotificationManager.IMPORTANCE_DEFAULT));
            builder.setChannelId("id");
        }
        startForeground(1,builder.build());

        return super.onStartCommand(intent, flags, startId);
    }
}